package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @create: 张曦文
 * 日期 :2025/11/3 14:49
 * 功能 :
 **/
@Component
@ConditionalOnClass(name = "javax.servlet.http.HttpServletRequest")
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的用户
        String userInfo = request.getHeader("user-info");
        // 2.判断是否为空
        if (StrUtil.isNotBlank(userInfo)) {
            try {
                // 保存到ThreadLocal
                UserContext.setUser(Long.valueOf(userInfo));
            } catch (NumberFormatException e) {
                // 处理无效的用户信息
                UserContext.removeUser();
            }
        } else {
            // 清除可能存在的旧数据
            UserContext.removeUser();
        }
        // 放行
        return true;
    }

}
